let fs = require('fs');
let path = require('path');
let router = require('koa-router')();

function searchControllers(defaultDir) {

    let files = fs.readdirSync(defaultDir);
    let resultFiles = files.filter((fileName) => {
        return fileName.endsWith('.js') && fileName !== 'index.js';
    });
    return resultFiles;
}


function registeForEachFile(files, currentPath) {

    files.forEach(item => {
        let tmpPath = path.join(currentPath, item);
        let routerObj = require(tmpPath);
        for (let r in routerObj) {
            let arrValue = routerObj[r];
            let type = routerObj[r][0];
            if (type === 'get') {
                if (arrValue.length === 2) {
                    let fn = arrValue[1];
                    router.get(r, fn);
                } else {
                    let auth = arrValue[1];
                    let fn = arrValue[2];
                    router.get(r, auth, fn);
                }
            } else {
                if (arrValue.length === 2) {
                    let fn = arrValue[1];
                    router.post(r, fn);
                } else {
                    let auth = arrValue[1];
                    let fn = arrValue[2];
                    router.post(r, auth, fn);
                }
            }
        }
    })
}

module.exports = function (dir) {
    let defaultDir = dir || '/controllers';
    let root = path.resolve('.');
    let resultControllerPath = path.join(root, defaultDir);
    let files = searchControllers(resultControllerPath);
    registeForEachFile(files, resultControllerPath);
    let fn = router.routes();
    return fn;
};